<?php

namespace App\Common\Traits\Admin;

use Exception;
use EasySwoole\ORM\DbManager;

use App\Common\Tools;

/**
 * @description: 后台创建数据
 */
trait Create
{
    /**
     * @description: 创建
     * @param {*}
     * @return {*}
     */
    public function create()
    {
        $result = DbManager::getInstance()->invoke(function ($client) {
            $param  = $this->request()->getRequestParam();
            $errMsg = $this->validateCreate($param);
            if ($errMsg !== true) {
                throw new Exception($errMsg, 405);
            }
            $model = $this->model::invoke($client);
            $mo    = false;
            if ($param[$this->id]) {
                $mo    = $model->getInfo($param[$this->id]);
            }
            $model->createData($param, $mo);
            return true;
        });
        $this->afterCreate($this->request()->getRequestParam());
        Tools::json($this->response(), 200, [], '数据修改完成');
    }

    /**
     * @description: 验证创建参数
     * @param array $param 前端参数
     * @return {*}
     */
    protected function validateCreate(array $param)
    {
        return true;
    }

    /**
     * @description: 创建后
     * @param array $param 前端参数
     * @return {*}
     */
    protected function afterCreate(array $param)
    {
        return true;
    }
}